﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DevComponents.DotNetBar;
using System.Speech.Synthesis;
using DTO;
using BUS;

namespace Support_Study_Vocabulary
{
    public partial class frmThemTu : Office2007Form
    {
        private ArrayList Words; //get all word from  data dictionary.        
        public SpeechSynthesizer _speaker;

        public frmThemTu()
        {
            InitializeComponent();
            Words = new ArrayList();
        }

        private void frmThemTu_Load(object sender, EventArgs e)
        {
            List<TOPIC> lsTopic = TopicBUS.getAllTopics();
            this.cbTopic.DisplayMember = "Name";
            this.cbTopic.ValueMember = "idTopic";
            this.cbTopic.DataSource = lsTopic;

            FileStream fsIn = new FileStream(".\\data\\Index.hl", FileMode.Open);
            BinaryReader brIn = new BinaryReader(fsIn, Encoding.UTF8);

            string tempWord = "";
            long flag = 0;
            long pos = 0;
            while (flag < fsIn.Length)
            {
                tempWord = brIn.ReadString();
                pos = brIn.ReadInt64();
                flag = fsIn.Position;
                Words.Add(new Index(tempWord, pos));
            }
            fsIn.Close();
        }      

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnViewList_Click(object sender, EventArgs e)
        {
            frmDanhSachTuVuaThem frm = new frmDanhSachTuVuaThem();
            frm.MdiParent = this.MdiParent;
            frm.LsSource = VocabularyBUS.getListVocabulariesbyDateToDate(DateTime.Today, DateTime.Today);
            frm._speaker = _speaker;
            frm.Show();
        }

        private void txtWord_Validated(object sender, EventArgs e)
        {
            if (!this.txtWord.Text.Equals(""))
            {
                long pos = Lookup(this.txtWord.Text);
                if (pos == -1)
                {
                    this.txtPho.Text = "";
                }
                else
                {
                    FileStream fsDt = new FileStream(".\\data\\Data.hl", FileMode.Open);
                    BinaryReader brDt = new BinaryReader(fsDt, Encoding.UTF8);
                    brDt.BaseStream.Seek(pos, SeekOrigin.Begin);
                    string mean = brDt.ReadString();
                    this.txtPho.Text = GetPhoneticize(mean);
                    fsDt.Close();
                }
            }
        }    

        private void chbNewTopic_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chbNewTopic.Checked == true)
            {
                this.cbTopic.Enabled = false;
                this.txtNewTopic.Enabled = true;
            }
            else
            {
                this.cbTopic.Enabled = true;
                this.txtNewTopic.Enabled = false;
            }
        }

        private void txtNewTopic_Validated(object sender, EventArgs e)
        {
            if (TopicBUS.getTopic(txtNewTopic.Text) != null)
            {
                MessageBox.Show("Chủ đề này đã có rồi.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);                
                this.txtNewTopic.Clear();
                this.txtNewTopic.Focus();
            }            
        }   
        
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.txtWord.Text.Equals(""))
            {
                MessageBox.Show("Từ mới không được bỏ trống.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (this.txtType.Text.Equals(""))
            {
                MessageBox.Show("Loại từ không được bỏ trống.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (this.chbNewTopic.Checked && this.txtNewTopic.Text.Equals(""))
            {
                MessageBox.Show("Chủ đề không được bỏ trống.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            try
            {                
                VOCABULARY vc = new VOCABULARY();
                vc.Word = this.txtWord.Text;
                vc.Type = this.txtType.Text;
                vc.Phoneticize = this.txtPho.Text;
                vc.MeanEng = this.txtMeanEng.Text;
                vc.MeanVi = this.txtMeanVi.Text;
                vc.idTopic = int.Parse(this.cbTopic.SelectedValue.ToString());
                vc.TopicDisplay = cbTopic.Text;
                vc.Date = this.dpkDate.Value;
                vc.isTwoWordVerb = 0;
                if (this.chbTwoWordVerb.Checked)
                {
                    vc.isTwoWordVerb = 1;
                }

                if (this.chbNewTopic.Checked == true)
                {
                    TOPIC tp = new TOPIC();
                    tp.Name = this.txtNewTopic.Text;                    

                    if (TopicBUS.Add(tp) == false)
                    {
                        MessageBox.Show("Tạo topic thất bại!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                                        
                    vc.idTopic = TopicBUS.getTopic(this.txtNewTopic.Text).idTopic;
                    List<TOPIC> ls = TopicBUS.getAllTopics();
                    this.cbTopic.DisplayMember = "Name";
                    this.cbTopic.ValueMember = "idTopic";
                    this.cbTopic.DataSource = ls;
                }

                VOCABULARY vcTemp = VocabularyBUS.getVocabulary(vc.Word, vc.Type, vc.idTopic);
                if (vcTemp == null)
                {
                    if (VocabularyBUS.Add(vc))
                    {
                        MessageBox.Show("Thêm thành công.", "Thông báo");
                        this.txtWord.Clear();
                        this.txtType.Clear();
                        this.txtMeanEng.Clear();
                        this.txtMeanVi.Clear();
                        //Speak spRead = new Speak();
                        //spRead.TextToWav("..//..//betray.mp3", "betray");
                        //this.cbBook.SelectedIndex = int.Parse(this.cbBook.SelectedValue.ToString());
                    }
                    else
                    {
                        MessageBox.Show("Thêm thất bại.", "Thông báo");
                        return;
                    }
                }
                else
                {
                    string report = "\"[word] ([type])\" thuộc chủ đề \"[topic]\" đã được thêm \"[date]\".";
                    report = report.Replace("[word]", vcTemp.Word);
                    report = report.Replace("[type]", vcTemp.Type);
                    report = report.Replace("[topic]", TopicBUS.getTopic(vcTemp.idTopic).Name);
                    report = report.Replace("[date]", string.Format("{0:dd - MM - yyyy}",vcTemp.Date));
                    MessageBox.Show(report, "Thông báo");
                    return;
                }                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        protected long Lookup(string str)
        {
            int left = 0, right = Words.Count - 1, mid = 0;
            while (left <= right)
            {
                mid = (left + right) / 2;
                string strRes = ((Index)Words[mid]).KeyWord;
                long pos = ((Index)Words[mid]).Position;
                if (str.ToUpper().Equals(strRes.ToUpper()))
                {
                    return pos;
                }
                else
                {
                    if (str.ToUpper().CompareTo(strRes.ToUpper()) < 0)
                    {
                        right = mid - 1;
                    }
                    else
                    {
                        left = mid + 1;
                    }
                }
            }
            return -1;
        }

        protected string GetPhoneticize(string str)
        {
            int begin = -1, end = -1;
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == '/')
                {
                    begin = i;
                    for (int j = begin + 1; j < str.Length; j++)
                    {
                        if (str[j] == '/')
                        {
                            end = j;
                            break;
                        }
                    }
                    break;
                }
            }
            if (begin == -1 || end == -1)
            {
                return "";
            }
            return str.Substring(begin, end - begin + 1);
        }                           
    }
}
